﻿using Newtonsoft.Json;
using SubVersionOne.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VersionOne.SDK.ObjectModel;
using VersionOne.SDK.ObjectModel.Filters;

namespace SubVersionOne
{
    public static class VersionOneProxy
    {
        
        /// <summary>
        /// can only be initialized by the login method
        /// </summary>
        private static  V1Instance instance;

        public static string LoggedInUser
        {
            get
            {
                return instance.LoggedInMember.Name;
            }
        }
        /// <summary>
        /// Login to VersionOne.  If any execption occurs we assume the login failed and return false.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="windowsAuth"></param>
        /// <returns></returns>
        public static Task<bool> Login(VersionOneCredentials credentials)
        {
            return System.Threading.Tasks.Task.Run<bool>(() =>
                {
                    
                    instance = new V1Instance(credentials.ApplicationUrl, credentials.UserName, credentials.Password, credentials.WindowsAuth);
                    try
                    {
                        instance.Validate();
                       // File.WriteAllText( JsonConvert.SerializeObject(credentials));
                       
                        return true;
                    }
                    catch(Exception ex)
                    {
                        //Logger.Info("{0}\n{1}", ex.Message, ex.StackTrace);
                        return false;
                    }
                });
        }

        public static System.Threading.Tasks.Task<List<SelectableItemViewModel>> GetWorkItems()
        {
            return System.Threading.Tasks.Task.Run<List<SelectableItemViewModel>>(() =>
                {
                    var results = new List<SelectableItemViewModel>();
                    List<string> items = new List<string>();
                    PrimaryWorkitemFilter filter = new PrimaryWorkitemFilter();
                    filter.State.Add(State.Active);
                    filter.Owners.Add(instance.LoggedInMember);

                    IterationFilter iterationFilter = new IterationFilter();
                    iterationFilter.State = new List<IterationState>
                    {
                         IterationState.Active
                    };

                    foreach (var it in instance.Get.Iterations(iterationFilter))
                    {
                        filter.Iteration.Add(it);
                    }

                    foreach (var wi in instance.Get.PrimaryWorkitems(filter).ToList())
                    {
                        TaskFilter tasks = new TaskFilter();

                        var story = new SelectableItemViewModel
                        {
                            ID = wi.DisplayID,
                            Name = wi.Name,
                             Description = wi.Description,
                              Url = wi.URL
                        };
                        results.Add(story);
                        story.Children = new System.Collections.ObjectModel.ObservableCollection<SelectableItemViewModel>();

                        if (SubVersionOne.ViewModelLocator.MainStatic.Settings.IncludeChildren)
                        {

                            foreach (var task in wi.GetSecondaryWorkitems(tasks))
                            {

                                if (!String.IsNullOrEmpty(task.DisplayID))
                                {
                                    story.Children.Add(new SelectableItemViewModel
                                        {
                                            ID = task.DisplayID,
                                            Name = task.Name,
                                            ParentID = story.ID,
                                            Description = task.Description,
                                            Url = task.URL

                                        });
                                }
                            }
                        }
                    }
                    return results;
                });
        }
    }
}
